import { useEffect, useState, useRef } from 'react'
const isFalsy = (value: any) => (value === 0 ? false : !value)
export function clearEmptyKey(obj: { [key: string]: unknown }) {
  console.log(obj)

  const temp = { ...obj }
  Object.keys(temp).forEach(key => {
    if (isFalsy(temp[key])) {
      delete temp[key]
    }
  })
  return temp
}

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback()
  }, [])
}

// 防抖函数
// export function useDebounce(value, delay = 1500) {
//   let timer;
//   return () => {
//     if (timer) clearTimeout(timer);
//     timer = setTimeout(() => {
//       console.log(value);
//       return value;
//     }, delay);
//   };
// }

// 使用泛型来规范类型
export const useDebounce = <T>(value: T, delay = 1500): T => {
  const [param, setParam] = useState(value)
  useEffect(() => {
    // 每次value变化,都会设置一个定时器
    const timer = setTimeout(() => setParam(value), delay)
    // 每次上一个useEffect运行完后执行
    return () => {
      clearTimeout(timer)
    }
  }, [value, delay])
  return param
}

//
export const useArray = <T>(initValue: T[]) => {
  const [value, setPersons] = useState(initValue)

  return {
    value,
    add: (person: T) => setPersons([...value, person]),
    removeIndex: (index: number) => {
      const tempPersons = [...value]
      tempPersons.splice(index, 1)
      setPersons(tempPersons)
    },
    clear: () => setPersons([])
  }
}

export const useDocumentTitle = (title: string, keepOnUnmounted: boolean = true) => {
  // 持久化 初始化title
  const oldTitle = useRef(document.title).current
  useEffect(() => {
    document.title = title
  }, [title])

  useEffect(() => {
    return () => {
      if (!keepOnUnmounted) {
        document.title = oldTitle
      }
    }
  }, [keepOnUnmounted, oldTitle])
}

// 重置路由,不但回到根路由, 而且还会刷新浏览器
export const resetRoute = () => (window.location.href = window.location.origin)

// 返回组件的挂载状态, 如果还没挂载或者已经卸载,返回false, 反之,返回true
//不允许做复制setData
export const useMountedRef = () => {
  const mountedRef = useRef(false)
  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  })
  return mountedRef
}
